#include "LinuxNetWidget.h"

#include <QComboBox>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QGroupBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QVBoxLayout>

#include <LinuxNetObject>
#include <LinuxNetRateObject>
#include <QTextStream>

LinuxNetWidget::LinuxNetWidget(QWidget *parent) : QWidget(parent) {
    QHBoxLayout *layout = new QHBoxLayout(this);
	
    QVBoxLayout *Leftlayout = new QVBoxLayout();
// left

// 1.1
    QGroupBox *leftBox = new QGroupBox("信息展示");
    // QVBoxLayout *leftBoxLayout = new QVBoxLayout(leftBox);
    Leftlayout->addWidget(leftBox);
    Leftlayout->addStretch();

    // 一个 QGridLayout

    QGridLayout *gridLayout = new QGridLayout(leftBox);

    for (auto &dev : LinuxNetObject::getDevNames())
    {
        QComboBox *temp = new QComboBox();
        temp->addItem(dev);
        comboBoxes.append(temp);
    }
    comboBoxes.append(new QComboBox);

    for (int i = 0; i < comboBoxes.size(); i++) {
        if (comboBoxes[i]->currentText().isEmpty())
            comboBoxes[i]->setEditable(true);
        // comboBoxes[i]->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
        
        LinuxNetObject *obj = new LinuxNetObject();

        QLabel *uploadLabel = new QLabel("------");
        QLabel *downloadLabel = new QLabel("------");

        gridLayout->addWidget(comboBoxes[i],       i, 0, 1, 1);
        gridLayout->addWidget(new QLabel("上传:"), i, 1);
        gridLayout->addWidget(uploadLabel , i, 2);
        gridLayout->addWidget(new QLabel("下载:"), i, 3);
        gridLayout->addWidget(downloadLabel, i, 4);

        connect(comboBoxes[i], &QComboBox::currentTextChanged, [=](const QString &text){
            obj->setDevName(text);
            // QTextStream(stdout) << text << "\n";
        });

        connect(obj, &LinuxNetObject::updateNet, [=](long upload, long download){
            uploadLabel->setText(LinuxNetRateObject::GetStringRateUnit(upload));
            downloadLabel->setText(LinuxNetRateObject::GetStringRateUnit(download));
            // QTextStream(stdout) << upload << "," << download << "\n";
        });

        obj->start();
        obj->setDevName(comboBoxes[i]->currentText());
        // QTextStream(stdout) << comboBoxes[i]->currentText() << "\n";

    }

    QVBoxLayout *Rightlayout = new QVBoxLayout();
// right

// 2.1
    // QGroupBox *rightBox = new QGroupBox("信息展示");
    // QVBoxLayout *rightBoxLayout = new QVBoxLayout(rightBox);
    // Rightlayout->addWidget(rightBox);
    
    layout->addLayout(Leftlayout,1);
    // layout->addLayout(Rightlayout,1);

    // resize(1200, 800);
    resize(470, 300);
}